# @FileName  : ocr.py
# @Time      : 2022/7/5 17:18
# @Author    : LuZhaoHui
# @Software  : PyCharm

from tool import *

WORDSPACECHAR = {'竖杠': '|', '逗号': ',', '空格': ' '}

def isCharUpToDown(cord1, cord2):
    # [x,y,w,h]
    b = False
    w2 = int(cord1[2] / 2)
    h2 = int(cord1[3] / 2)
    a1 = cord1[2] * cord1[3]
    a2 = cord2[2] * cord2[3]
    while True:
        a = abs(a1 - a2) * 100
        aMax = max(a1, a2)
        diff = a / aMax
        # 面积相差<10%
        if diff > 60.0:
            break
        # y坐标位于相差高度的一半
        if (cord2[1] - cord1[1]) < h2:
            break
        if cord2[1] > (cord1[1] + 2 * cord1[3]):
            break
        # x坐标位于相差宽度的一半
        if abs(cord1[0] - cord2[0]) > w2:
            break
        b = True
        break
    return b

# 转换成有效的多个汉字
def isLineToCode(chars):
    codes = []
    for code in chars:
        # print(code)
        if isHz(code['code']):
            codes.append(code)
    return codes

def isStrToHz(chars):
    codes = ''
    for ch in chars:
        if isHz(ch):
            codes += ch
    return codes

def procOcrResult(name):
    file, data = getOcrResultFile(name)
    x = data['coords'][0]
    y = data['coords'][1]
    w = data['coords'][4]
    h = data['coords'][5]
    # 增加边框面积
    lines1 = []  # 单个字组成串
    lineStr = []
    lineStr0 = []  # 左->右字符串
    lineStr1 = []  # 右->左字符串
    lineStr2 = []  # 上->下字符串
    for line in data['lines']:
        # 分析行:1个字符，分数<600
        codes = isLineToCode(line['chars'])
        if len(codes) <= 0:
            continue
        if len(codes) <= 2:
            # 2个汉字
            for code in codes:
                code['ok'] = 0
                code['x'] = w - code['coords'][2]
                code['y'] = code['coords'][1]
                code['w'] = code['coords'][4] - code['coords'][0]
                code['h'] = code['coords'][5] - code['coords'][1]
                lines1.append(code)
        else:
            lineStr.append(line['text'])
            lineStr0.append(strToJianti(line['text']))
            lineStr1.append(strToJianti(line['text'][::-1]))
    lines1.sort(key=lambda x: (x['y'], x['x']))
    for i, line in enumerate(lines1):
        if line['ok']:
            continue
        if line['score'] < 600:
            continue
        line2 = lines1[i + 1:]
        lines1[i]['ok'] = 1
        chs = line['code']
        c1 = [line['x'], line['y'], line['w'], line['h']]
        if len(line2) > 0:
            for j, c in enumerate(line2):
                # 寻找上下匹配字符
                if c['ok']:
                    continue
                c2 = [c['x'], c['y'], c['w'], c['h']]
                if isCharUpToDown(c1, c2):
                    lines1[i + j + 1]['ok'] = 1
                    chs += c['code']
                    c1 = c2
        lineStr2.append(chs)
    for s in lineStr2:
        if len(s) > 1:
            lineStr0.append(strToJianti(s))
    line0 = ''
    line1 = ''
    line2 = ''
    n0 = 0
    n1 = 0
    n2 = 0
    bname = os.path.splitext(os.path.basename(name))[0]
    file0 = os.path.join(os.path.dirname(name), '%s-0.txt' % (bname))
    file1 = os.path.join(os.path.dirname(name), '%s-1.txt' % (bname))
    file2 = os.path.join(os.path.dirname(name), '%s-2.txt' % (bname))
    f0 = open(file0, 'a', encoding='utf-8')
    f1 = open(file1, 'a', encoding='utf-8')
    f2 = open(file2, 'a', encoding='utf-8')
    for s in lineStr:
        if len(line0) > 0:
            line0 += '|'
        line0 += s
        n0 += 1
        f0.write('%d:%s\n' % (n0, s))
    for s in lineStr0:
        if len(line1) > 0:
            line1 += '|'
            line2 += '|'
        hzs = strToHz(s)
        if len(hzs) <= 1:
            continue
        line1 += hzs
        n1 += 1
        f1.write('%d:%s\n' % (n1, hzs))
        pys = strToPinYin(hzs)
        line2 += pys
        n2 += 1
        f2.write('%d:%s\n' % (n2, pys))
    for s in lineStr1:
        if len(line1) > 0:
            line1 += '|'
            line2 += '|'
        hzs = strToHz(s)
        if len(hzs) <= 1:
            continue
        line1 += hzs
        n1 += 1
        f1.write('%d:%s\n' % (n1, hzs))
        pys = strToPinYin(hzs)
        line2 += pys
        n2 += 1
        f2.write('%d:%s\n' % (n2, pys))
    f0.close()
    f1.close()
    f2.close()
    return line0, line1, line2

